<?php
class mdl_member_info extends ujn_model {

	function addMoney($uid, $money, $sflag) {
		$mid = $this->uint($uid);
		$smoney = $this->uint($money);

		if ( $mid < 1 || $smoney < 1 ) {
			return false;
		}

		$smoney = $sflag == 0 ? $smoney : -1*$smoney;

		if( $sflag == 0 ) { //加钱操作, 限制单次最大加钱数目
			$smoney = min( 500000, $smoney );
		}

		$query = "UPDATE {$this->tbl_name_info} SET `money` = `money` + '$smoney' WHERE mid = '$mid' AND `money` + '$smoney' >= 0;";

		$this->_db->query( $query );
		return $this->_db->affectedRows();
	}

	function makeMember($mid, $money = 1000, $invite_uid = 0, $invite_way = 0) {
		$flag = false;
		if($money > 100000) return $flag;

		$pu = json_decode(urldecode($_POST['user']), true);
		$_sql_1 = "insert into {$this->tbl_name_game} set `mid` = '$mid', `exp` = '1', `money` = '$money', `wintimes` = '0', `losetimes` = '0';";
		$_sql_2 = "insert into {$this->tbl_name_info} set `mid` = '$mid', `level` = '1', `mstatus` = '0', `mactivetime` = '" . NOW . "', 
															`mentercount` = '1', `mtime` = '" . NOW . "', `puid` = '{$pu['puid']}', 
																`invite_uid` = '{$invite_uid}', `invite_way` = '{$invite_way}';";
		$this->_db->query($_sql_1);
		$this->_db->query($_sql_2);
		if($this->_db->affectedRows()>0) {
			mdl_log_winlog::getInstance()->addWin($mid, mdl_log_winlog::GET_REGISTER_REWARD, 0, $money, '', '', 0);

			$this->redis_power('puid_to_mid', 'sachiel')->set(mdl_ckey::getck(mdl_ckey::puid_to_mid, $pu['puid']), $mid, false, false);
			
			$flag = true;
		} 
		unset($pu);
		
		return $flag;
	}

	// 增加登录次数
	function incSignIned($mid, $user) {
		$_sql_1 = "update {$this->tbl_name_info} set `mactivetime` = '" . NOW . "', mentercount = mentercount + 1 where mid = '{$mid}';";
		$_sql_2 = "update {$this->tbl_name_game} set `drunk_degree` = '0' where mid = '{$mid}';";
		$this->_db->query($_sql_1);
		$this->_db->query($_sql_2);
		
		if($this->redis_power('puid_to_mid', 'sachiel') != false) {
			$loginInfo = $this->getLianxuLogin($mid);
			
			if(date('Ymd', $user['mactivetime']) == date('Ymd', strtotime('yesterday'))) {
				$successive = $loginInfo['successive'] + 1; 
				$this->setLianxuLoginSuccessive($mid, $successive, $loginInfo);
			}else {
				$this->setLianxuLoginSuccessive($mid, 1, $loginInfo);
			}

			// 设置可以领取登录奖励
			$this->setLianxuLoginRewarded($mid, 1);
		}	

		$member_gamebasic = ujn_runtime::getParam('member_gamebasic');
		if(!empty($member_gamebasic) && is_object($this->mc('minfo_mid_' . ($mid%4), 'sachiel'))) {
			$user['drunk_degree'] = 0;
			$user['mactivetime'] = NOW;
			$user['mentercount'] = $user['mentercount'] + 1;
			$this->mc('minfo_mid_' . ($mid%4), 'sachiel')->set("minfo_mid.{$member_gamebasic['mid']}", $member_gamebasic, 86400);
		}
	}
	
	function updateFields($mid, $fields) {
		if(!$mid = tls_func::uint($mid)) return false;
		
		if(empty($fields) || !is_array($fields)) return false;
		
		$af = array();
		foreach($fields as $k => $f) {
			if(!in_array( $k, array('drunk_degree'), true )) {
				continue;
			}
			$af[] = "`{$k}`='{$f}'";
		}
		if(empty($af)) return false;
		
		$_sql = "UPDATE {$this->tbl_name_game} SET " . implode(',', $af) . " WHERE mid = '{$mid}' ";
		$this->_db->query($_sql);
		
		return true;
	}	

	// 设置用户配置
	function setMemberSetting($mid, $type, $value) {
		$setting_ck = mdl_ckey::getck(mdl_ckey::user_setting, $mid);

		$set		= $this->mc()->get($setting_ck);
		$set_data	= false == $set ? array() : json_decode($set, true);

		$set_data[$type] = $value;

		return $this->mc()->set($setting_ck, json_encode($set_data));
	}

	// 获取用户配置
	function getMemberSetting($mid) {
		$set		= $this->mc()->get(mdl_ckey::getck(mdl_ckey::user_setting, $mid));
		$set_data	= false == $set ? array() : json_decode($set, true);
		return $set_data;
	}

	function getMemberByMIDs_useCache($mids = array(), $fields = '') {

		// 过滤非法字段,
		$fields = $this->escape($fields);
		if(!is_array($mids) || count($mids) == 0 || empty($fields)) return array();

		$fields = explode(',', $fields);
		foreach($fields as $k => $f) {
			if(!in_array($f, array( 'puid', 'money', 'mid', 'level', 'exp', 'mtime' ))) unset($fields[$k]);
		}

		// 过滤超长好友数
		$max_query_count = 1000;
		if(count($mids) > $max_query_count) {
			$mids = array_slice($mids, 0, $max_query_count);
		}

		// 缓存中没有查询到的puid列表
		$un_incache_mids = array();

		// 构造key
		$keys = array();
		foreach($mids as $mid) {
			$mid = tls_func::uint($mid);
			if(!$mid) continue;

			$keys[$mid%4][] = "minfo_mid.{$mid}";		//KEY取余
			$un_incache_mids[$mid] = '1';
		}
		if(empty($un_incache_mids)) return array( );

		// 查询memcache
		$c = array();
		foreach($keys as $ckey => $key) {
			$aRet = $this->mc('minfo_mid_' . $ckey, 'sachiel')->getMulti($key);
			if(is_array($aRet) && !empty($aRet)) {
				foreach($aRet as $xc) {
					if(isset($un_incache_mids[$xc['mid']])) {
						unset($un_incache_mids[$xc['mid']]);
					}
					$c[] = $xc;
				}
			}			
		}
		unset($mids, $keys, $aRet);

		// memcache 中查询结果不足
		if(is_array($un_incache_mids) && !empty($un_incache_mids)) {
			$mids = '\''. implode('\', \'', array_keys($un_incache_mids)) . '\'';

			// 查询mysql, 并回写memcache
			$_sql_1 = "select * from {$this->tbl_name_game} where mid in ($mids)";
			$_sql_2 = "select * from {$this->tbl_name_info} where mid in ($mids)";
			$_result_1 = $this->_db->getAll($_sql_1, MYSQL_ASSOC);
			$_result_2 = $this->_db->getAll($_sql_2, MYSQL_ASSOC);
			
			$caches = array();
			if(!empty($_result_1)) {
				foreach($_result_1 as $data) {
					if(!empty($data)) $caches["minfo_mid.{$data['mid']}"] = $data;
				}
				foreach($_result_2 as $data) {
					if(isset($caches["minfo_mid.{$data['mid']}"]) && !empty($caches["minfo_mid.{$data['mid']}"]) && !empty($data)) {
						$caches["minfo_mid.{$data['mid']}"] = array_merge($caches["minfo_mid.{$data['mid']}"], $data);
					}
					
					$saveInfo[$mid%4]["minfo_mid.{$data['mid']}"] = $caches["minfo_mid.{$data['mid']}"];
				}
				
				foreach( $saveInfo as $sk => $i ) {
					$this->mc('minfo_mid_' . $sk, 'sachiel')->setMulti($i, 86400);
				}

				// 将查询结果合并到 $c
				$c = array_merge($c, $caches);
			}
			unset($_result_1, $_result_2, $saveInfo, $caches, $un_incache_mids);
		}
		
		// 只查询fields规定范围内的数据
		foreach($c as $k => $data) {
			foreach((array)$data as $field_key => $null) {
				if(!in_array($field_key, $fields))
					unset($c[$k][$field_key]);
			}
		}
		return array_values($c);
	}

	function getMemberByPUIDs($puids = array(), $fields = '') {
		// 过滤非法字段
		$fields = $this->escape($fields);
		if(!is_array($puids) || count($puids) == 0 || empty($fields)) return array();

		$fields = explode(',', $fields);
		foreach($fields as $k => $f) {
			if(!in_array($f, array( 'puid', 'money', 'mid', 'level', 'exp' ))) unset($fields[$k]);
		}

		$fields = '`' . implode('`,`', $fields) . '`';
		$puids = '\''. implode('\', \'', $puids) . '\'';

		$_sql = "select {$fields} from {$this->tbl_name_info} where `puid` in ($puids);";
		return $this->_db->getAll($_sql, MYSQL_ASSOC);
	}

	function getMember($mid) {
		$_sql_1 = "select * from {$this->tbl_name_game} where `mid` = '$mid' limit 1;";
		$_sql_2 = "select * from {$this->tbl_name_info} where `mid` = '$mid' limit 1;";
		$_result_1 = $this->_db->getOne($_sql_1, MYSQL_ASSOC);
		$_result_2 = $this->_db->getOne($_sql_2, MYSQL_ASSOC);
		
		$m = array_merge($_result_1, $_result_2);
		
		//每次登陆更新MC
		$sk = $mid%4;
		$this->mc('minfo_mid_' . $sk, 'sachiel')->set("minfo_mid.{$mid}", $m);
		
		return $m;
	}

	function getMemberByUID4Flash($mid, $invite_uid = 0, $invite_way = 0) {

		$d = $this->getMember($mid);
		
		if(empty($d)) {
			$d['money'] = 2000;
			$this->makeMember($mid, $d['money'], $invite_uid, $invite_way);
			
			$d['wintimes'] = $d['losetimes'] = 0;
			$d['level'] = $d['exp'] = 1;
			$d['mactivetime'] = $d['mtime'] = NOW;
			
			$d['is_register'] = 1;
		} else {
			// 更新用户等级信息 
			$exp_level = 0;
			foreach((array)ujn::getCFG('system.member_level') as $lv => $detail) {
				if($d['exp'] < $detail[0]) {
					$exp_level = $lv;
					break;
				}
			}

			if(($d['level'] < $exp_level)) {
				$d['level'] = $exp_level;
				$_sql = "update {$this->tbl_name_info} set `level` = '$exp_level' where mid = '{$mid}';";	
				$this->_db->query($_sql);
			}
			
			// 添加运行时缓存, 用户基本信息
			ujn_runtime::setParam('member_gamebasic', $d);
		}

		return $d;
	}

	protected function __construct() {
		parent::__construct();
		$this->db_name			= GAME;
		$this->tbl_name_game	= "`{$this->db_name}`.`" . GAME . "_member_game`"; 	//
		$this->tbl_name_info	= "`{$this->db_name}`.`" . GAME . "_member_info`"; 	//
		$this->_db				= $this->mysql();
	}


    /**
     * 单例模型
     * @return mdl_member_info
     */
	static function getInstance() {
        return parent::getInstance(__CLASS__);
	}
}